using Microsoft.Extensions.Options;
using MongoDB.Driver;
using newsApi.Models;

namespace newsApi.Services;

public class ChanelsService
{
    private readonly IMongoCollection<Chanel> _chanelsCollection;
    public ChanelsService(IOptions<NewsLibDatabaseSettings> newsLibDatabaseSettings)
    {
        var mongoClient = new MongoClient(
            newsLibDatabaseSettings.Value.ConnectionString);

        var mongoDatabase = mongoClient.GetDatabase(
            newsLibDatabaseSettings.Value.DatabaseName);

        _chanelsCollection = mongoDatabase.GetCollection<Chanel>(
            newsLibDatabaseSettings.Value.ChanelsCollectionName);

    }

    public async Task<List<Chanel>> GetAsync() =>
        await _chanelsCollection.Find(_ => true).ToListAsync();
        
    public async Task CreateAsyn(Chanel newChanel) =>
        await _chanelsCollection.InsertOneAsync(newChanel);

    public async Task<Chanel?> GetAsync(string id) =>
        await _chanelsCollection.Find(x =>x.Id ==id).FirstOrDefaultAsync();
    
    public async Task UpdateAsync(string id,Chanel updateChanel) =>
        await _chanelsCollection.ReplaceOneAsync(x => x.Id==id,updateChanel);

    public async Task RemoveAsync(string id) =>
        await _chanelsCollection.DeleteOneAsync(x => x.Id==id);
}